package site.teamo.biu.net.common.web.configuration;

import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import site.teamo.biu.net.common.web.entity.SystemConfig;
import site.teamo.biu.net.common.web.entity.SystemConfigDO;
import site.teamo.biu.net.common.web.mapper.SystemConfigMapper;
import site.teamo.biu.tool.core.cache.MemorySessionCache;
import site.teamo.biu.tool.core.cache.SessionCache;
import site.teamo.biu.tool.core.util.CaptchaFactory;
import site.teamo.biu.tool.spring.listener.ApplicationReadyListener;

/**
 * @author haocongshun
 * @date 2023/02/22 11:09:59
 */
@Slf4j
@Configuration
public class PassportConfiguration {

    public static final String USERNAME = "admin";
    public static final SystemConfig PASSWORD = new SystemConfig("password", "管理员账号密码", false, () -> "30a70b06db2a7278172b54c264615922");

    @Value("${biu-net.session.timeout:36000000}")
    private long sessionTimeout;

    @Value("${sso.captcha.width:200}")
    private int width;

    @Value("${sso.captcha.height:50}")
    private int height;

    @Resource
    private SystemConfigMapper systemConfigMapper;

    @Autowired
    private ApplicationReadyListener listener;

    @PostConstruct
    public void init() {
        listener.addJob("管理员用户信息初始化", () -> {
            SystemConfigDO password = systemConfigMapper.selectById(PASSWORD.id());
            if (password == null) {
                systemConfigMapper.insert(PASSWORD.toSystemConfigDO());
            }
        });
    }

    @Bean
    public SessionCache<String> sessionCache() {
        return new MemorySessionCache<>(sessionTimeout);
    }

    @Bean
    public CaptchaFactory captchaFactory() {
        return CaptchaFactory.builder()
                .setWidth(width)
                .setHeight(height)
                .addCodeGenerator(new RandomGenerator(4))
                .addCodeGenerator(new MathGenerator(1))
                .build();
    }

}
